/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.db;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import blueprint4j.utils.BindStringInterface;

public class FieldStringRegEx extends FieldString implements BindStringInterface {
	private static final long serialVersionUID = 1L;
	private String regExpression;
	private String help;

	public FieldStringRegEx(String p_name, int p_field_type, String p_description,int length,String regExpression,String help, Entity entity) {
		super(p_name, p_field_type, p_description,length, entity);
		this.regExpression=regExpression;
		this.help=help;
	}

	public Field newInstance(Entity entity) {
		return new FieldStringRegEx(getName(), getFieldType(), getDescription(),getLength(),regExpression,help, entity);
	}
	
    /**
     */
    public boolean isRegExValid(String string) {
        Pattern pattern = Pattern.compile(regExpression);
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }
	
	 /**
     * Overwrite this to create a field type with specific validity requirements. Returns the issue with the field.
     * 
     * @return
     */
	public String isInvalid() {
		if (get()==null || isRegExValid(get())){
			return null;
		}
		return getDescription()+" value '"+get()+"' is invalid.\n"+help;
	}

}
